package com.example.exercise.controller;

import com.example.exercise.job.ScheduleUtil;
import com.example.exercise.job.MyJob1;
import com.example.exercise.job.MyJob2;
import jakarta.annotation.PostConstruct;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class QuartzDemoController {

    @Autowired
    private Scheduler scheduler;

    /**
     * 定时器初始化
     */
    @PostConstruct
    public void init(){
        ScheduleUtil.createOrUupdateJob(scheduler, "demo1", MyJob1.class);
        ScheduleUtil.createOrUupdateJob(scheduler, "demo2", MyJob2.class);
    }

    @GetMapping("addJob")
    public String addJob() throws SchedulerException {
        String groupId = "demo1";
        ScheduleUtil.createOrUupdateJob(scheduler, groupId, MyJob1.class);
        return "addJob成功";
    }

    @GetMapping("deleteJob")
    public String deleteJob() throws SchedulerException {
        String groupId = "demo1";
        ScheduleUtil.deleteJob(scheduler, groupId);
        JobDetail detail = scheduler.getJobDetail(new JobKey(groupId));
        System.err.println(detail);
        return "删除任务成功";
    }

    @GetMapping("resumeJob")
    public String resumeJob() throws SchedulerException {
        String groupId = "demo1";
        JobDetail detail = scheduler.getJobDetail(new JobKey(groupId));
        if(detail == null) {
            return "任务不存在，或者被删除，恢复任务失败";
        }
        ScheduleUtil.resumeJob(scheduler, groupId);
        return "resumeJob成功";
    }

    @GetMapping("pauseJob")
    public String pauseJob() throws SchedulerException {
        String groupId = "demo1";
        JobDetail detail = scheduler.getJobDetail(new JobKey(groupId));
        if(detail == null) {
            return "任务不存在，或者被删除，停止任务失败";
        }
        ScheduleUtil.pauseJob(scheduler, groupId);
        return "pauseJob成功";
    }

    //运行一次
    @GetMapping("runJob")
    public String runJob() throws SchedulerException {
        String groupId = "demo1";
        JobDetail detail = scheduler.getJobDetail(new JobKey(groupId));
        if(detail == null) {
            return "任务不存在，或者被删除，运行一次任务";
        }
        ScheduleUtil.run(scheduler, groupId);
        return "runJob一次成功";
    }
}
